package com.example.kotlin

import android.content.Intent
import com.example.core.base.BaseActivity
import com.example.core.base.BasePresenter
import com.example.core.utils.CacheUtil
import com.example.core.utils.ToastUtil
import com.example.kotlin.databinding.ActivityMainBinding
import com.example.kotlin.entity.User
import com.example.lesson.LessonActivity

class MainActivity : BaseActivity<ActivityMainBinding, BasePresenter>() {

    override fun initViewBinding() = ActivityMainBinding.inflate(layoutInflater)

    private val userNameKey = "userName"
    private val userPwdKey = "userPwd"

    override fun initData() {

    }

    override fun initListener() {
        viewBinding.apply {
            codeView.setOnClickListener {
                codeView.updateCode()
            }
            btnLogin.setOnClickListener {
                login()
            }
        }
    }

    override fun initView() {
        viewBinding.apply {
            etUsername.setText(CacheUtil.get(userNameKey))
            etPassword.setText(CacheUtil.get(userPwdKey))
        }
    }

    override fun initPresenter(): BasePresenter = BasePresenter()

    private fun login() {
        val name = viewBinding.etUsername.text.toString().trim()
        val pwd = viewBinding.etPassword.text.toString().trim()
        val code = viewBinding.etCode.text.toString().trim()
        val user = User(name, pwd, code)
        if (verify(user)) {
            CacheUtil.save(userNameKey, name)
            CacheUtil.save(userPwdKey, pwd)
            startActivity(Intent(this, LessonActivity::class.java))
        }
    }

    private fun verify(user: User): Boolean {
        if (user.userName.length < 4) {
            ToastUtil.showToast(getString(R.string.user_name_no_verify))
            return false
        }
        if (user.password.length < 4) {
            ToastUtil.showToast(getString(R.string.user_pwd_no_verify))
            return false
        }
        /*if (user.code != viewBinding.codeView.text.toString().trim()) {
            ToastUtil.showToast(getString(R.string.user_code_no_verify))
            return false
        }*/
        return true
    }
}
